package com.jk.util;

import org.apache.ibatis.javassist.*;
import org.apache.ibatis.javassist.bytecode.*;
import org.apache.ibatis.javassist.bytecode.annotation.Annotation;

/**
 * Created by yanghuan on 2016/1/25.
 */
public class AnnotationUtil {

    //给类增加注解
    public static void addAnnotationToClass(String className, String annotationName) throws NotFoundException {
        ClassPool pool = ClassPool.getDefault();
        CtClass ct = pool.get(className);
        ClassFile cf = ct.getClassFile();
        ConstPool cp = cf.getConstPool();
        AnnotationsAttribute attribute = new AnnotationsAttribute(cp, AnnotationsAttribute.visibleTag);
        Annotation annotation = new Annotation(annotationName, cp);
        attribute.setAnnotation(annotation);
        cf.addAttribute(attribute);
    }

    //清除类的注解
    public static void removeAnnotationToClass(String className) throws NotFoundException {
        ClassPool pool = ClassPool.getDefault();
        CtClass ct = pool.get(className);
        ClassFile cf = ct.getClassFile();
        ConstPool cp = cf.getConstPool();
        AnnotationsAttribute attribute = new AnnotationsAttribute(cp, AnnotationsAttribute.visibleTag);
        cf.addAttribute(attribute);
    }

    public static void main(String[] args) throws NotFoundException, ClassNotFoundException {
        ClassPool pool = ClassPool.getDefault();
        //获取要修改的类的所有信息
        CtClass ct = pool.get("com.jk.util.quartz.DisConcurrentJob");
        ClassFile cf = ct.getClassFile();
        ConstPool cp = cf.getConstPool();
        AnnotationsAttribute attribute = new AnnotationsAttribute(cp, AnnotationsAttribute.visibleTag);
//        Annotation annotation = new Annotation("org.quartz.DisallowConcurrentExecution", cp);
//        attribute.setAnnotation(annotation);
        cf.addAttribute(attribute);

        Object[] annotations = ct.getAnnotations();
        for (Object object : annotations) {
            System.out.println(object);
        }
    }

}
